package cn.tedu.charging.service;

import cn.tedu.charging.common.pojo.param.ProgressCostParam;
import cn.tedu.charging.common.pojo.po.ChargingCostRulePO;
import cn.tedu.charging.common.pojo.vo.ProgressCostVO;
import cn.tedu.charging.dao.repository.CostRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;

@Service
@Slf4j
public class CostService {

    @Autowired
    private CostRepository costRepository;
    @Autowired
    private StringRedisTemplate  stringRedisTemplate;
    public ProgressCostVO calculate(ProgressCostParam param) {
        //获取价格数据
      ChargingCostRulePO costRulePO =  getCostRule(param,LocalDateTime.now().getHour());
      //根据价格计算单次金额
       BigDecimal cost = calculateCost(param,costRulePO);
       //使用redis执行incrby做缓存累加
        BigDecimal totalCost =  accumulateCost(param.getOrderNo(),cost);
        ProgressCostVO vo = new ProgressCostVO();
        vo.setTotalCost(totalCost.doubleValue());
        vo.setPowerFee(costRulePO.getPowerFee().doubleValue());
        return vo;
    }

    private BigDecimal accumulateCost(String orderNo, BigDecimal cost) {
        String orderKey="charging:order:total:"+orderNo;
        Double increment = stringRedisTemplate.opsForValue().increment(orderKey, cost.doubleValue());
        return new BigDecimal(increment);
    }

    private BigDecimal calculateCost(ProgressCostParam param, ChargingCostRulePO costRulePO) {
        BigDecimal bigDecimal = new BigDecimal(param.getChargingCapacity());
        BigDecimal powerFee = costRulePO.getPowerFee();
        BigDecimal cost = bigDecimal.multiply(powerFee).setScale(2,BigDecimal.ROUND_HALF_UP);
        return cost;
    }

    private ChargingCostRulePO getCostRule(ProgressCostParam param, int hour) {
        return costRepository.getCostRule(param.getStationId(),hour);
    }
}
